package com.wisezone.studentmanager.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.tomcat.util.buf.HexUtils;

/**
 * Java消息摘要算法 MD5 工具类,其实其他摘要算法的实现也类似
 */
public class MD5Util {

	public static String md5Encode(String content) {
		return md5Encode(content,null);
	}
	
	public static String md5Encode(String content, Object salt) {
		// JDK 6 支持以下6种消息摘要算法，不区分大小写
		// md5,sha(sha-1),md2,sha-256,sha-384,sha-512
		String encodeStr = "";
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			encodeStr = HexUtils.toHexString(md.digest(mergeContentAndSalt(content,salt).getBytes()));
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return encodeStr;
	}

	public static String mergeContentAndSalt(String content, Object salt) {
		if (content == null) {
			content = "";
		}
		if ((salt == null) || "".equals(salt)) 
			return content;
			
		return content + "{" + salt.toString() + "}";
	}

	// 一个简版测试
	public static void main(String[] args) throws NoSuchAlgorithmException {
		String m1 = md5Encode("123456","salt");
		System.out.println("m1=" + m1);
	}
}
